<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author:  <1227187938@qq.com>
// +----------------------------------------------------------------------
// 应用公共文件
use app\admin\model\Config as ConfigModel;
use app\home\model\ContentModel;
use think\Log;
function AdminLogDetail($Data=array())
{
    $request = request();
    $Node= $request->module().'/'.$request->controller().'/'. $request->action();
    $Model=db('admin_log');
    $Data['LogAdminID']=session('AdminID');
    $Data['LogOperateNode']=$Node;
    $Data['LogOperateIP']=$request->ip();
    $Data['LogOperateTime']=time();
    $Model->insert($Data);
}
/**
 * 字符串截取，支持中文和其他编码
 * static
 * access public
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 * return string
 */
function msubstr($str,$start=0,$length,$charset="utf-8",$suffix=true){
    if(function_exists("mb_substr"))
        $slice=mb_substr($str,$start,$length,$charset);
    elseif(function_exists('iconv_substr')){
        $slice = iconv_substr($str,$start,$length,$charset);
        if(false===$slice){$slice = '';}
    }else{
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice : $slice;
}
/**
 * 获取静态文件配置
 * @param cachename    文件名称
 * @return            array
 */
function get_cache($cachename)
{
    $cache_file_path = APP_PATH . "extra/cache_" . $cachename . ".php";
	@include $cache_file_path;
    return $data;
}
function refresh_cache()
{
    global $db;
    $config_arr = array();
    $cache_file_path = APP_PATH . "extra/cache_config.php";
   // $sql = "SELECT * FROM " . table($cachename);
	$Model=db('config');
    $arr = $Model->select();
    foreach ($arr as $key => $val) {
        $config_arr[$val['name']] = $val['value'];
    }
    write_static_cache($cache_file_path, $config_arr);
}
//缓存文件
function write_static_cache($cache_file_path, $config_arr)
{
    $content = "<?php\r\n";
    $content .= "\$data = " . var_export($config_arr, true) . ";\r\n";
    $content .= "?>";
    if (!file_put_contents($cache_file_path, $content, LOCK_EX)) {
        $fp = @fopen($cache_file_path, 'wb+');
        if (!$fp) {
            exit('生成缓存文件失败');
        }
        if (!@fwrite($fp, trim($content))) {
            exit('生成缓存文件失败');
        }
        @fclose($fp);
    }
}
//支付宝支付接口调用
function AliPayApiCall($OrderNumber,$PayMoney)
{
    $SystemParam=include APP_PATH.'extra/cache_config.php';
    $alipay_config=include APP_PATH.'common/org/alipay/alipay.config.php';
    include APP_PATH.'common/org/alipay/lib/alipay_submit.class.php';
    /**************************请求参数**************************/
    //支付类型
    $payment_type = "1";
    //必填，不能修改
    //服务器异步通知页面路径
    $notify_url = config('DomainName').url('payrequest/alipay_notify');
    //需http://格式的完整路径，不能加?id=123这类自定义参数
    //页面跳转同步通知页面路径
    $return_url = config('DomainName').url('payrequest/done',['ordernumber'=>$OrderNumber]);
    //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/
    //商户订单号
    $out_trade_no = $OrderNumber;
    //商户网站订单系统中唯一订单号，必填
    //订单名称
    $subject = '在线支付';
    //必填
    //付款金额
    $total_fee = $PayMoney;
    //必填
    //订单描述
    $body = '';
    //商品展示地址
    $show_url = '';
    //需以http://开头的完整路径，例如：http://www.商户网址.com/myorder.html
    //防钓鱼时间戳
    $anti_phishing_key = "";
    //若要使用请调用类文件submit中的query_timestamp函数
    //客户端的IP地址
    $exter_invoke_ip = "";
    //非局域网的外网IP地址，如：221.0.0.1
    /************************************************************/
//构造要请求的参数数组，无需改动
    $parameter = array(
        "service" => "create_direct_pay_by_user",
        "partner" => trim($alipay_config['partner']),
        "seller_email" => trim($alipay_config['seller_email']),
        "payment_type"	=> $payment_type,
        "notify_url"	=> $notify_url,
        "return_url"	=> $return_url,
        "out_trade_no"	=> $out_trade_no,
        "subject"	=> $subject,
        "total_fee"	=> $total_fee,
        "body"	=> $body,
        "show_url"	=> $show_url,
        "anti_phishing_key"	=> $anti_phishing_key,
        "exter_invoke_ip"	=> $exter_invoke_ip,
        "_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
    );
    //建立请求
    $alipaySubmit = new AlipaySubmit($alipay_config);
    $html_text = $alipaySubmit->buildRequestForm($parameter,"post", "支付宝支付");
    $Sign=$alipaySubmit->buildRequestPara($parameter);
    $Back=array();
    $Back['HTML']=$html_text;
    $Back['Sign']=$Sign['sign'];
    return $Back;
}
//支付宝扫描支付接口调用
function AliPaySaoMaApiCall($OrderNumber,$PayMoney)
{
    $config=array();
    require_once APP_PATH.'common/org/alipaysaoma/f2fpay/model/builder/AlipayTradePrecreateContentBuilder.php';
    require_once APP_PATH.'common/org/alipaysaoma/f2fpay/service/AlipayTradeService.php';
    // 创建请求builder，设置请求参数
    $qrPayRequestBuilder = new AlipayTradePrecreateContentBuilder();
    $qrPayRequestBuilder->setOutTradeNo($OrderNumber);
    $qrPayRequestBuilder->setTotalAmount($PayMoney);
    $qrPayRequestBuilder->setSubject('在线支付');
    // 调用qrPay方法获取当面付应答
    //dump($config);
    $qrPay = new AlipayTradeService($config);
    $qrPayResult = $qrPay->qrPay($qrPayRequestBuilder);
    $qrPayResult->getTradeStatus();
    $response = $qrPayResult->getResponse();
    $Back='';
    if(!empty($response->qr_code)) $Back=$response->qr_code;
    return urlencode($Back);
}
//支付宝支付成功返回调用，即：支付宝服务器异步请求 $Type=1 会员 2代理商
//支付宝扫描支付成功返回调用，即：支付宝服务器异步请求
function AliSaoMaPayApiNotifyCall()
{
    require_once APP_PATH.'common/org/alipaysaoma/f2fpay/service/AlipayTradeService.php';
    if (!empty($_POST['out_trade_no'])&& trim($_POST['out_trade_no'])!=""){
        ////获取商户订单号
        $out_trade_no = trim($_POST['out_trade_no']);
        //第三方应用授权令牌,商户授权系统商开发模式下使用
        $appAuthToken = "";//根据真实值填写
        //构造查询业务请求参数对象
        $queryContentBuilder = new AlipayTradeQueryContentBuilder();
        $queryContentBuilder->setOutTradeNo($out_trade_no);
        $queryContentBuilder->setAppAuthToken($appAuthToken);
        //初始化类对象，调用queryTradeResult方法获取查询应答
        $queryResponse = new AlipayTradeService($config);
        $queryResult = $queryResponse->queryTradeResult($queryContentBuilder);
        //根据查询返回结果状态进行业务处理
        switch ($queryResult->getTradeStatus()){
            case "SUCCESS":
                //echo "支付宝查询交易成功:"."<br>--------------------------<br>";
                //print_r($queryResult->getResponse());
                PayOperationDispose($out_trade_no,'',2);
                break;
        }
        return ;
    }
}
//微信二维码调用
function WeiXinErWeiMaCall($OrderNumber,$OrderMoney)
{
    $SystemParam=include APP_PATH.'extra/systemparam.php';
    require_once APP_PATH.'common/org/wxpay/lib/WxPay.Api.php';
    require_once APP_PATH.'common/org/wxpay/example/WxPay.NativePay.php';
    require_once APP_PATH.'common/org/wxpay/example/log.php';
    define('APPID',$SystemParam['WXAPPID']);
    define('MCHID',$SystemParam['WXMCHID']);
    define('KEY',$SystemParam['WXKEY']);
    define('APPSECRET',$SystemParam['WXAPPSECRET']);
    $notify = new NativePay();
    $input = new WxPayUnifiedOrder();
    $input->SetBody("在线支付");
    $input->SetAttach("");
    $input->SetOut_trade_no($OrderNumber);
    $input->SetTotal_fee($OrderMoney*100);
    $input->SetTime_start(date("YmdHis"));
    $input->SetTime_expire(date("YmdHis", time() + 600));
    $input->SetGoods_tag("");
    //$input->SetNotify_url('http://192.168.0.188:196/home/clearing/weixinpay_notify.html');
    $input->SetNotify_url(config('DomainName').url('payrequest/weixinpay_notify'));
    $input->SetTrade_type("NATIVE");
    $input->SetProduct_id("");
    $result = $notify->GetPayUrl($input);
    if(empty($result["code_url"])){
        $result=array();
        $result['code_url']='';
        $result['sign']='';
    }
    $url = $result["code_url"];
    $Data=urlencode($url);
    $Back=array();
    $Back['Sign']=$result['sign'];
    $Back['Data']=$Data;
    return $Back;
}
//微信服务器异步调用
function WeiXinPayApiNotifyCall()
{
    require_once APP_PATH.'common/org/wxpay/example/notify.php';
}
function CreateErWeiMaImg($Data)
{
    //vendor("phpqrcode.phpqrcode");
    require_once APP_PATH.'common/org/wxpay/example/phpqrcode/phpqrcode.php';
    //生成二维码图片
    $Data = urldecode($Data);
    QRcode::png($Data,false,QR_ECLEVEL_L,7);
}
//支付成功后订单处理业务
function PayOperationDispose($OrderNumber,$Sign='')
{
	//$text= $OrderNumber.'==========================='.date('Y-m-d H:i:s');
	//write_log($text,'_pay_log.txt',1);
    $PayTime=time();
    $Where=array();
    $Where['BalanceNumber']=$OrderNumber;
    $Where['BalancePayState']='0';
    $Info=db('balance')->where($Where)->find();
    if(!empty($Info)){
		//更新支付状态
		//db('member')->where('MemberID',$Info['BalanceMemberID'])->setInc('MemberBalanceCount',$Info['BalanceCount']);
		$Data1=array();
		$Data2=array();
		//更新支付状态
		$Data1['ispaystate']='1';
		$Data1['ispaytime']=$PayTime;
		db('member')->where('MemberID',$Info['BalanceMemberID'])->update($Data1);

		$ContentextModel = new ContentextModel();
		$data2['isstate']=7;
		$ContentextModel->modContentExt($Info['BalanceMemberID'],$data2,5);
        $Data=array();
        $Data['BalanceNumber']=$OrderNumber;
        $Data['BalancePayState']='1';
        $Data['BalancePayTime']=$PayTime;
        db('balance')->where($Where)->update($Data);
    }
}
//Json 中汉字转换
function encode_json($Array)
{
    $str=json_encode($Array);
    return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', create_function( '$matches', 'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");' ), $str);
}
//使用 fsockopen 实现PHP异步请求
function doRequest($url, $param=array()){
    $urlinfo = parse_url($url);
    $host = $urlinfo['host'];
    $path = $urlinfo['path'];
    $query = isset($param)? http_build_query($param) : '';
    $port = 80;
    $errno = 0;
    $errstr = '';
    $timeout = 10;
    $fp = fsockopen($host, $port, $errno, $errstr, $timeout);
    $out = "POST ".$path." HTTP/1.1\r\n";
    $out .= "host:".$host."\r\n";
    $out .= "content-length:".strlen($query)."\r\n";
    $out .= "content-type:application/x-www-form-urlencoded\r\n";
    $out .= "connection:close\r\n\r\n";
    $out .= $query;
    fputs($fp, $out);
    fclose($fp);
}
function deldir($dir)
{
    $dh = @opendir($dir);
    while($file =readdir($dh))
    {
        if($file!="." && $file!="..")
        {
            $fullpath = $dir."/".$file;
            @unlink($fullpath);
        }
    }
}
//删除目录
function DeleteDir($dir)
{
    //dump($dir);
	die;
    //先删除目录下的文件：
    $dh = @opendir($dir);
    while ($file = readdir($dh)) {
        if($file != "." && $file!="..") {
            $fullpath = $dir."/".$file;
            if(!is_dir($fullpath)) {
                @unlink($fullpath);
            } else {
                DeleteDir($fullpath);
            }
        }
    }
    closedir($dh);
    //删除当前文件夹：
    if(@rmdir($dir)) {
        return true;
    } else {
        return false;
    }
}
/**
 * @ string 需要转换的文字
 * @ encoding 目标编码
 **/
function detect_encoding($string,$encoding = 'gbk'){
    $is_utf8 = preg_match('%^(?:[\x09\x0A\x0D\x20-\x7E]| [\xC2-\xDF][\x80-\xBF]| \xE0[\xA0-\xBF][\x80-\xBF] | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} | \xED[\x80-\x9F][\x80-\xBF] | \xF0[\x90-\xBF][\x80-\xBF]{2} | [\xF1-\xF3][\x80-\xBF]{3} | \xF4[\x80-\x8F][\x80-\xBF]{2} )*$%xs',$string);
    if($is_utf8 && $encoding == 'utf8'){
        return $string;
    }else if($is_utf8){
        return mb_convert_encoding($string, $encoding, "UTF-8");
    }else{
        return mb_convert_encoding($string, $encoding, 'gbk,gb2312,big5');
    }
}
function order_num()
{
	$date = date('Ymd');
	$str = substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
	$rand = rand(10, 100);
	return $date . $str . $rand;
}
function isMobilet()
{
	$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
	$is_pc = (strpos($agent, 'windows nt')) ? true : false;
	$is_mac = (strpos($agent, 'mac os')) ? true : false;
	$is_iphone = (strpos($agent, 'iphone')) ? true : false;
	$is_android = (strpos($agent, 'android')) ? true : false;
	$is_ipad = (strpos($agent, 'ipad')) ? true : false;
	if($is_pc){
		return  false;
	}
	if($is_mac){
		return  true;
	}
	if($is_iphone){
		return  true;
	}
	if($is_android){
		return  true;
	}
	if($is_ipad){
		return  true;
	}
}
function ToUrlParams($arr)
{
    $buff = "";
    foreach ($arr as $k => $v)
    {
        if($k != "sign" && $v != "" && !is_array($v)){
            $buff .= $k . "=" . $v . "&";
        }
    }
    $buff = trim($buff, "&");
    return $buff;
}
  function  curl_w($url,$data){
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
                curl_setopt($ch, CURLOPT_POST, TRUE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
                $output=curl_exec($ch);
                curl_close($ch);
                return $output;
        }

/*
 * 改变手机号码格式
 * @param $mobile string 号码
 * @return string
 */
function division_mobile($mobile)
{
    $new_tel = substr($mobile, 0, 3) . '-' . substr($mobile, 3, 4) . '-' . substr($mobile, 7, 11);
    return $new_tel;
}
//时间转行函数
function transfer_time($time)
{
    $rtime = date("m-d H:i",$time);
    $htime = date("H:i",$time);

    $time = time() - $time;

    if ($time < 60)
    {
        $str = '刚刚';
    }
    elseif ($time < 60 * 60)
    {
        $min = floor($time/60);
        $str = $min.'分钟前';
    }
    elseif ($time < 60 * 60 * 24)
    {
        $h = floor($time/(60*60));
        $str = $h.'小时前 '.$htime;
    }
    elseif ($time < 60 * 60 * 24 * 3)
    {
        $d = floor($time/(60*60*24));
        if($d==1)
            $str = '昨天 '.$rtime;
        else
            $str = '前天 '.$rtime;
    }
    else
    {
        //$str = $rtime;
		$str='刚刚';
    }
    return $str;
}

function str_membername($str){

	//判断是否包含中文字符
	if(preg_match("/[\x{4e00}-\x{9fa5}]+/u", $str)) {
		//按照中文字符计算长度
		$len = mb_strlen($str, 'UTF-8');
		//echo '中文';
		if($len >= 3){
			//三个字符或三个字符以上掐头取尾，中间用*代替
			$str = mb_substr($str, 0, 2, 'UTF-8') . '***' . mb_substr($str, -1, 1, 'UTF-8');
		} elseif($len == 2) {
			//两个字符
			$str = mb_substr($str, 0, 1, 'UTF-8') . '*';
		}
	} else {
		//按照英文字串计算长度
		$len = strlen($str);
		//echo 'English';
		if($len >= 3) {
			//三个字符或三个字符以上掐头取尾，中间用*代替
			$str = substr($str, 0, 1) . '***' . substr($str, -1);
		} elseif($len == 2) {
			//两个字符
			$str = substr($str, 0, 1) . '*';
		}
	}
	return $str;
}

function msubstrprice($str,$start=0,$length,$charset="utf-8",$suffix=true){
    if(function_exists("mb_substr"))
        $slice=mb_substr($str,$start,$length,$charset);
    elseif(function_exists('iconv_substr')){
        $slice = iconv_substr($str,$start,$length,$charset);
        if(false===$slice){$slice = '';}
    }else{
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }
    return $suffix ? $slice.'' : $slice;
}
// 字符串双层MD5加密
function encrypt_string($string)
{
    //return md5(md5($string));
	return md5(md5('ABC123zyx()'.trim($string)));
}

// 生成唯一标识符
function get_uniqid()
{
    return encrypt_string(uniqid(mt_rand(), true));
}

// 清洗html代码的空白符号
function clear_html_blank($string)
{
    $string = str_replace("\r\n", '', $string); // 清除换行符
    $string = str_replace("\n", '', $string); // 清除换行符
    $string = str_replace("\t", '', $string); // 清除制表符
    $string = str_replace(' ', '', $string); // 清除大空格
    $string = str_replace('&nbsp;', '', $string); // 清除 &nbsp;
    $string = preg_replace('/\s+/', ' ', $string); // 清除空格
    return $string;
}
// 获取用户IP
function get_user_ip()
{
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $cip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $cip = $_SERVER['HTTP_CLIENT_IP'];
    } else {
        $cip = $_SERVER['REMOTE_ADDR'];
    }
    if ($cip == '::1') { // 使用localhost时
        $cip = '127.0.0.1';
    }
    if (! preg_match('/^[0-9\.]+$/', $cip)) { // 非标准的IP
        $cip = 'unknow';
    }
    return htmlspecialchars($cip);
}

// 生成无限极树,$data为二维数组数据
function get_tree($data, $tid, $idField, $pidField, $sonName = 'son')
{
    $tree = array();
    foreach ($data as $key => $value) {
        if (is_array($value)) {
            if ($value[$pidField] == "$tid") { // 父亲找到儿子
                $value[$sonName] = get_tree($data, $value[$idField], $idField, $pidField, $sonName);
                $tree[] = $value;
            }
        } else {
            if ($value->$pidField == "$tid") { // 父亲找到儿子
                $temp = clone $value;
                $temp->$sonName = get_tree($data, $value->$idField, $idField, $pidField, $sonName);
                $tree[] = $temp;
            }
        }
    }
    return $tree;
}
	// 获取当前访问域名
function get_http_host($noport = true)
{
    if ($noport) {
        return str_replace(':' . $_SERVER['SERVER_PORT'], '', $_SERVER['HTTP_HOST']);
    } else {
        return $_SERVER['HTTP_HOST'];
    }
}
// 服务器信息
function get_server_info()
{
    // 定义输出常量
    define('YES', 'Yes');
    define('NO', '<span style="color:red">No</span>');

    // 服务器系统
    $data['php_os'] = PHP_OS;
    // 服务器访问地址
    $data['http_host'] = $_SERVER['HTTP_HOST'];
    // 服务器名称
    $data['server_name'] = $_SERVER['SERVER_NAME'];
    // 服务器端口
    $data['server_port'] = $_SERVER['SERVER_PORT'];
    // 服务器地址
    $data['server_addr'] = isset($_SERVER['LOCAL_ADDR']) ? $_SERVER['LOCAL_ADDR'] : $_SERVER['SERVER_ADDR'];
    // 服务器软件
    $data['server_software'] = $_SERVER['SERVER_SOFTWARE'];
    // 站点目录
    $data['document_root'] = isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : DOC_PATH;
    // PHP版本
    $data['php_version'] = PHP_VERSION;
    // 数据库驱动
    $data['db_driver'] = 'Mysql';
    // php配置文件
    $data['php_ini'] = @php_ini_loaded_file();
    // 最大上传
    $data['upload_max_filesize'] = ini_get('upload_max_filesize');
    // 最大提交
    $data['post_max_size'] = ini_get('post_max_size');
    // 最大提交文件数
    $data['max_file_uploads'] = ini_get('max_file_uploads');
    // 内存限制
    $data['memory_limit'] = ini_get('memory_limit');
    // 检测gd扩展
    $data['gd'] = extension_loaded('gd') ? YES : NO;
    // 检测imap扩展
    $data['imap'] = extension_loaded('imap') ? YES : NO;
    // 检测socket扩展
    $data['sockets'] = extension_loaded('sockets') ? YES : NO;
    // 检测curl扩展
    $data['curl'] = extension_loaded('curl') ? YES : NO;
    // 会话保存路径
    $data['session_save_path'] = session_save_path() ?: $_SERVER['TMP'];
    // 检测standard库是否存在
    $data['standard'] = extension_loaded('standard') ? YES : NO;
    // 检测多线程支持
    $data['pthreads'] = extension_loaded('pthreads') ? YES : NO;
    // 检测XCache支持
    $data['xcache'] = extension_loaded('XCache') ? YES : NO;
    // 检测APC支持
    $data['apc'] = extension_loaded('APC') ? YES : NO;
    // 检测eAccelerator支持
    $data['eaccelerator'] = extension_loaded('eAccelerator') ? YES : NO;
    // 检测wincache支持
    $data['wincache'] = extension_loaded('wincache') ? YES : NO;
    // 检测ZendOPcache支持
    $data['zendopcache'] = extension_loaded('Zend OPcache') ? YES : NO;
    // 检测memcache支持
    $data['memcache'] = extension_loaded('memcache') ? YES : NO;
    // 检测memcached支持
    $data['memcached'] = extension_loaded('memcached') ? YES : NO;
    // 已经安装模块
    $loaded_extensions = get_loaded_extensions();
    $extensions = '';
    foreach ($loaded_extensions as $key => $value) {
        $extensions .= $value . ', ';
    }
    $data['extensions'] = $extensions;
    return json_decode(json_encode($data));
}

function delete_dir_file($dir_name) {
    $result = false;
    if(is_dir($dir_name)){
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DS . $item)) {
                        delete_dir_file($dir_name . DS . $item);
                    } else {
                        unlink($dir_name . DS . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }

    return $result;
}
 /**
 * JS提示跳转
 * @param  $tip  弹窗口提示信息(为空没有提示)
 * @param  $type 设置类型 close = 关闭 ，back=返回 ，refresh=提示重载，jump提示并跳转url
 * @param  $url  跳转url
 */
function alert($tip = "", $type = "", $url = "") {
	$js="<meta http-equiv='Content-Type'' content='text/html; charset=utf-8'>";
	$js.= "<script>";
	if ($tip)
		$js .= "alert('" . $tip . "');";
	switch ($type) {
		case "close" : //关闭页面
			$js .= "window.close();";
			break;
		case "back" : //返回
			$js .= "history.back(-1);";
			break;
		case "refresh" : //刷新
			$js .= "parent.location.reload();";
			break;
		case "top" : //框架退出
			if ($url)
				$js .= "top.location.href='" . $url . "';";
			break;
		case "jump" : //跳转
			if ($url)
				$js .= "window.location.href='" . $url . "';";
			break;
		default :
			break;
	}
	$js .= "</script>";
	echo $js;
	if($type)exit();
}
// 写入缓存
function cache_config($refresh = false)
{
	// 系统配置缓存
	$Post=array();
	$Str1='';
	$model = new ConfigModel();
	$config_cache = RUNTIME_PATH . '/config/' . md5('config') . '.php';
	if (! file_exists($config_cache) || $refresh) {
		create_file(RUNTIME_PATH.'config/'. md5('config').'.php', $content = null, $over = false);
		$model = new ConfigModel();
		$Post=$model->getConfig();
		$Str1='<?php'."\r\n";
        $Str1.='return ';
        $Str1.=var_export($Post,true);
        $Str1.=';';
        file_put_contents(RUNTIME_PATH.'config/'. md5('config').'.php',$Str1);
		$config = require RUNTIME_PATH . '/config/' . md5('config') . '.php';
	}else{
		$config = require RUNTIME_PATH . '/config/' . md5('config') . '.php';
	}
	return $config;
}
/**
 * 跳转
 *
 * @param string $url跳转地址
 */
function location($url)
{
    if ($url == '-1' && isset($_SERVER['HTTP_REFERER'])) {
        $url = $_SERVER['HTTP_REFERER'];
        if (strpos($url, get_http_url()) !== 0) {
            $url = '/';
        }
    }
    header('Location:' . $url);
    exit();
}

/**
 * 弹窗并跳转
 *
 * @param string $info信息
 * @param string $url跳转地址
 */
function alert_location($info, $url, $status = 0)
{
   if ($url == '-1' && isset($_SERVER['HTTP_REFERER'])) {
      $url = $_SERVER['HTTP_REFERER'];
      if (strpos($url, get_http_url()) !== 0) {
          $url = '/';
      }
   }
	echo '<script type="text/javascript">alert("' . clear_html_blank($info) . '");location.href="' . $url . '";</script>';
	exit();
}

/**
 * 弹窗并关闭
 *
 * @param string $info信息
 */
function alert_close($info, $status = 0)
{
     echo '<script type="text/javascript">alert("' . clear_html_blank($info) . '");window.close();</script>';
     exit();
}
// 获取当前访问地址
function get_http_url($noport = false)
{
    if (is_https()) {
        $url = 'https://' . $_SERVER['HTTP_HOST'];
    } else {
        $url = 'http://' . $_SERVER['HTTP_HOST'];
    }
    if ($noport) {
        $url = str_replace(':' . $_SERVER['SERVER_PORT'], '', $url);
    }
    return $url;
}
// 判断当前是否为https
function is_https()
{
    if ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) {
        return true;
    } else {
        return false;
    }
}
// 检测目录是否存在
function check_dir($path, $create = false)
{
    if (is_dir($path)) {
        return true;
    } elseif ($create) {
        return create_dir($path);
    }
}

// 创建目录
function create_dir($path)
{
    if (! file_exists($path)) {
        if (mkdir($path, 0777, true)) {
            return true;
        }
    }
    return false;
}

// 检查文件是否存在
function check_file($path, $create = false, $content = null)
{
    if (file_exists($path)) {
        return true;
    } elseif ($create) {
        return create_file($path, $content);
    }
}

// 创建文件
function create_file($path, $content = null, $over = false)
{
    if (file_exists($path) && ! $over) {
        return false;
    } elseif (file_exists($path)) {
        @unlink($path);
    }
    check_dir(dirname($path), true);
    $handle = fopen($path, 'w') or error('创建文件失败，请检查目录权限！');
    fwrite($handle, $content);
    return fclose($handle);
}

// 目录文件夹列表
function dir_list($path)
{
    $list = array();
    if (! is_dir($path) || ! $filename = scandir($path)) {
        return $list;
    }
    $files = count($filename);
    for ($i = 0; $i < $files; $i ++) {
        $dir = $path . '/' . $filename[$i];
        if (is_dir($dir) && $filename[$i] != '.' && $filename[$i] != '..') {
            $list[] = $filename[$i];
        }
    }
    return $list;
}

// 目录文件列表
function file_list($path)
{
    $list = array();
    if (! is_dir($path) || ! $filename = scandir($path)) {
        return $list;
    }
    $files = count($filename);
    for ($i = 0; $i < $files; $i ++) {
        $dir = $path . DS . $filename[$i];
        if (is_file($dir)) {
            $list[] = $filename[$i];
        }
    }
    return $list;
}

// 目录下文件及文件夹列表
function path_list($path)
{
    $list = array();
    if (! is_dir($path) || ! $filename = scandir($path)) {
        return $list;
    }
    $files = count($filename);
    for ($i = 0; $i < $files; $i ++) {
        $dir = $path . '/' . $filename[$i];
        if (is_file($dir) || (is_dir($dir) && $filename[$i] != '.' && $filename[$i] != '..')) {
            $list[] = $filename[$i];
        }
    }
    return $list;
}

/**
 * 删除目录及目录下所有文件或删除指定文件
 *
 * @param str $path
 *            待删除目录路径
 * @param int $delDir
 *            是否删除目录，true删除目录，false则只删除文件保留目录
 * @return bool 返回删除状态
 */
function path_delete($path, $delDir = false)
{
    $result = true; // 对于空目录直接返回true状态
    if (! file_exists($path)) {
        return $result;
    }
    if (is_dir($path)) {
        if (! ! $dirs = scandir($path)) {
            foreach ($dirs as $value) {
                if ($value != "." && $value != "..") {
                    $dir = $path . '/' . $value;
                    $result = is_dir($dir) ? path_delete($dir, $delDir) : unlink($dir);
                }
            }
            if ($result && $delDir) {
                return rmdir($path);
            } else {
                return $result;
            }
        } else {
            return false;
        }
    } else {
        return unlink($path);
    }
}

// 判断文件是否是图片
function is_image($path)
{
    $types = '.gif|.jpeg|.png|.bmp'; // 定义检查的图片类型
    if (file_exists($path)) {
        $info = getimagesize($path);
        $ext = image_type_to_extension($info['2']);
        if (stripos($types, $ext) !== false)
            return true;
    }
    return false;
}

/**
 * 文件上传
 *
 * @param string $input_name表单名称
 * @param string $file_ext允许的扩展名
 * @param number $max_width最大宽度
 * @param number $max_height最大高度
 * @return string 返回成功上传文件的路径数组
 */
function upload($input_name, $file_ext = null, $filwjename='',$max_width = null, $max_height = null, $watermark = false)
{
    // 未选择文件返回空
    if (! isset($_FILES[$input_name])) {
        return '文件超过PHP环境允许的大小！';
    } else {
        $files = $_FILES[$input_name];
    }

    // 定义允许上传的扩展
    $array_ext_allow = explode(',', $file_ext);
    $array_save_file = array();
    if (is_array($files['tmp_name'])) { // 多文件情况
        $file_count = count($files['tmp_name']);
        for ($i = 0; $i < $file_count; $i ++) {
            if (! $files['error'][$i]) {
                $upfile = handle_upload($files['name'][$i], $files['tmp_name'][$i],$filwjename, $array_ext_allow, $max_width, $max_height, $watermark);
                if (strrpos($upfile, '/') > 0) {
                    $array_save_file[] = $upfile;
                } else {
                    $err = $upfile;
                }
            } else {
                $err = '错误代码' . $files['error'][$i];
            }
        }
    } else { // 单文件情况
        if (! $files['error']) {
            $upfile = handle_upload($files['name'], $files['tmp_name'],$filwjename, $array_ext_allow, $max_width, $max_height, $watermark);
            if (strrpos($upfile, '/') > 0) {
                $array_save_file[] = $upfile;
            } else {
                $err = $upfile;
            }
        } else {
            $err = '错误代码' . $files['error'];
        }
    }
    if (isset($err)) {
        return $err;
    } else {
        return $array_save_file;
    }
}

// 处理并移动上传文件
function handle_upload($file, $temp,$filwjename, $array_ext_allow, $max_width, $max_height, $watermark)
{
    // 定义主存储路径
    $save_path = 'uploads';

    $file = explode('.', $file); // 分离文件名及扩展
    $file_ext = strtolower(end($file)); // 获取扩展

    if (! in_array($file_ext, $array_ext_allow)) {
        return $file_ext . '格式的文件不允许上传！';
    }

    $image = array(
        'png',
        'jpg',
		'jpeg',
        'gif',
        'bmp'
    );
    $file = array(
        'rar',
        'doc',
        'docx',
        'zip'
    );
    if (in_array($file_ext, $image)) {
        $file_type = 'image';
    } elseif (in_array($file_ext, $file)) {
        $file_type = 'file';
    } else {
        $file_type = 'other';
    }
   if(!empty($filwjename)){

		 // 检查文件存储路径
		if (! check_dir($save_path . '/' . $file_type . '/' .$filwjename.'/'. date('Ymd'), true)) {
			return '存储目录创建失败！';
		}
		$file_path = $save_path . '/' . $file_type . '/' .$filwjename.'/'. date('Ymd') . '/' . time() . mt_rand(100000, 999999) . '.' . $file_ext;
	}else{
		 // 检查文件存储路径
		if (! check_dir($save_path . '/' . $file_type . '/'.date('Ymd'), true)) {
			return '存储目录创建失败！';
		}
		$file_path = $save_path . '/' . $file_type . '/' . date('Ymd') . '/' . time() . mt_rand(100000, 999999) . '.' . $file_ext;
	}
    if (! move_uploaded_file($temp, $file_path)) { // 从缓存中转存
        return '从缓存中转存失败！';
    }
    $save_file = str_replace(ROOT_PATH, '/', $file_path); // 获取文件站点路径
    // 如果是图片
    if (is_image($file_path)) {
        // 进行等比例缩放
        /*if (($reset = resize_img($file_path, $file_path, $max_width, $max_height)) !== true) {
            return $reset;
        }*/
        // 图片打水印
        if ($watermark) {
            watermark_img($file_path);
        }
    }
    return $save_file;
}

/**
 * *
 * 等比缩放图片
 *
 * @param string $src_image源图片路径
 * @param string $out_image输出图像路径
 * @param number $max_width最大宽
 * @param number $max_height最大高
 * @param number $img_quality图片质量
 * @return boolean 返回是否成功
 */
function resize_img($src_image, $out_image = null, $max_width = null, $max_height = null, $img_quality = 90)
{
    // 输出地址
    if (! $out_image)
        $out_image = $src_image;

    // 读取配置文件设置
    if (! $max_width)
        $max_width = 800 ?: 999999999;
    if (! $max_height)
        $max_height = 600 ?: 999999999;

    // 获取图片属性
    list ($width, $height, $type, $attr) = getimagesize($src_image);

    // 检查输出目录
    check_dir(dirname($out_image), true);

    // 无需缩放的图片
    if ($width <= $max_width && $height <= $max_height) {
        if ($src_image != $out_image) { // 存储地址不一致时进行拷贝
            if (! copy($src_image, $out_image)) {
                return '缩放图片时拷贝到目的地址失败！';
            }
        }
        return true;
    }

    // 求缩放比例
    if ($max_width && $max_height) {
        $scale = min($max_width / $width, $max_height / $height);
    } elseif ($max_width) {
        $scale = $max_width / $width;
    } elseif ($max_height) {
        $scale = $max_height / $height;
    }

    if ($scale < 1) {
        switch ($type) {
            case 1:
                $img = imagecreatefromgif($src_image);
                break;
            case 2:
                $img = imagecreatefromjpeg($src_image);
                break;
            case 3:
                $img = imagecreatefrompng($src_image);
                break;
        }

        $new_width = floor($scale * $width);
        $new_height = floor($scale * $height);
        $new_img = imagecreatetruecolor($new_width, $new_height); // 创建画布

        // 创建透明画布,避免黑色
        if ($type == 1 || $type == 3) {
            $color = imagecolorallocate($new_img, 255, 255, 255);
            imagefill($new_img, 0, 0, $color);
            imagecolortransparent($new_img, $color);
        }
        imagecopyresized($new_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

        switch ($type) {
            case 1:
                imagegif($new_img, $out_image, $img_quality);
                break;
            case 2:
                imagejpeg($new_img, $out_image, $img_quality);
                break;
            case 3:
                imagepng($new_img, $out_image, $img_quality / 10); // $quality参数取值范围0-99 在php 5.1.2之后变更为0-9
                break;
            default:
                imagejpeg($new_img, $out_image, $img_quality);
        }
        imagedestroy($new_img);
        imagedestroy($img);
    }
    return true;
}

// 剪切图片
function cut_img($src_image, $out_image = null, $new_width = null, $new_height = null, $img_quality = 90)
{
    // 输出地址
    if (! $out_image)
        $out_image = $src_image;

    // 读取配置文件设置
    if (! $new_width && ! $new_height)
        return;

    // 获取图片属性
    list ($width, $height, $type, $attr) = getimagesize($src_image);
    switch ($type) {
        case 1:
            $img = imagecreatefromgif($src_image);
            break;
        case 2:
            $img = imagecreatefromjpeg($src_image);
            break;
        case 3:
            $img = imagecreatefrompng($src_image);
            break;
    }

    // 不限定是等比例缩放
    if (! $new_width) {
        $new_width = floor($width * ($new_height / $height));
    }
    if (! $new_height) {
        $new_height = floor($height * ($new_width / $width));
    }

    // 计算裁剪是变大缩小方式
    if ($width >= $new_width && $height >= $new_height) { // 长宽均满足
        $cut_width = $new_width;
        $cut_height = $new_height;
    } else { // 有一边不满足
        $scale1 = $width / $new_width;
        $scale2 = $height / $new_height;
        if ($scale1 < $scale2) { // 变化越多的一边取全值，其余一边等比例缩放
            $cut_width = $width;
            $cut_height = floor($height * ($width / $new_width));
        } else {
            $cut_width = floor($new_width * ($height / $new_height));
            $cut_height = $height;
        }
    }

    // 创建画布
    $new_img = imagecreatetruecolor($new_width, $new_height);

    // 创建透明画布,避免黑色
    if ($type == 1 || $type == 3) {
        $color = imagecolorallocate($new_img, 255, 255, 255);
        imagefill($new_img, 0, 0, $color);
        imagecolortransparent($new_img, $color);
    }

    imagecopyresized($new_img, $img, 0, 0, 0, 0, $new_width, $new_height, $cut_width, $cut_height);
    check_dir(dirname($out_image), true); // 检查输出目录

    switch ($type) {
        case 1:
            imagegif($new_img, $out_image, $img_quality);
            break;
        case 2:
            imagejpeg($new_img, $out_image, $img_quality);
            break;
        case 3:
            imagepng($new_img, $out_image, $img_quality / 10); // $quality参数取值范围0-99 在php 5.1.2之后变更为0-9
            break;
        default:
            imagejpeg($new_img, $out_image, $img_quality);
    }
    imagedestroy($new_img);
    imagedestroy($img);
    return true;
}

// 图片水印
function watermark_img($src_image, $out_image = null, $position = null, $watermark_image = null, $watermark_text = '', $watermark_text_size = null, $watermark_text_color = null)
{
    if (! Config::get('watermark_open')) {
        return;
    }

    // 输出地址
    if (! $out_image)
        $out_image = $src_image;

    // 如果不存在文字及图片则直接返回
    if (! $watermark_text) {
        $watermark_text = Config::get('watermark_text') ?: '';
    }
    $watermark_image = $watermark_image ?: Config::get('watermark_pic');
    if (! $watermark_text && ! $watermark_image) {
        return;
    }

    // 获取图片属性
    list ($width1, $height1, $type1, $attr1) = getimagesize($src_image);
    switch ($type1) {
        case 1:
            $img1 = imagecreatefromgif($src_image);
            break;
        case 2:
            $img1 = imagecreatefromjpeg($src_image);
            break;
        case 3:
            $img1 = imagecreatefrompng($src_image);
            break;
    }

    if ($watermark_image) {
        $watermark_image = ROOT_PATH . $watermark_image;
        // 获取水印图片
        list ($width2, $height2, $type2, $attr2) = getimagesize($watermark_image);
        switch ($type2) {
            case 1:
                $img2 = imagecreatefromgif($watermark_image);
                break;
            case 2:
                $img2 = imagecreatefromjpeg($watermark_image);
                break;
            case 3:
                $img2 = imagecreatefrompng($watermark_image);
                break;
        }
    } else {
        if (! $watermark_text_size) {
            $watermark_text_size = Config::get('watermark_text_size') ?: 16;
        }
        if (! $watermark_text_color) {
            $watermark_text_color = Config::get('watermark_text_color') ?: '100,100,100';
        }
        $colors = explode(',', $watermark_text_color);

        if (Config::get('watermark_text_font')) {
            $font = ROOT_PATH . Config::get('watermark_text_font');
        } else {
            return;
        }

        // 手动创建水印图像
        $fontsize = $watermark_text_size;
        $width2 = mb_strlen($watermark_text, 'UTF-8') * ($fontsize + 10) + 20;
        $height2 = $fontsize + 10;
        $img2 = imagecreatetruecolor($width2, $height2);
        $color = imagecolorallocate($img2, 255, 255, 255);
        imagefill($img2, 0, 0, $color);
        imagecolortransparent($img2, $color); // 创建透明图
        $textcolor = imagecolorallocate($img2, $colors[0], $colors[1], $colors[2]);
        imagettftext($img2, $fontsize, 0, 5, $fontsize + 5, $textcolor, $font, $watermark_text);
    }

    // 现对图片太大时，自动缩放水印
    if ($width1 < $width2 * 3 || $height1 < $height2) {
        $scale = min(($width1 / 3) / $width2, ($height1 / 2) / $height2); // 求缩放比例
        $new_width = floor($scale * $width2);
        $new_height = floor($scale * $height2);
    } else {
        $new_width = $width2;
        $new_height = $height2;
    }

    // 水印位置
    if (! $position) {
        $position = Config::get('watermark_position') ?: 4;
    }
    switch ($position) {
        case '1':
            $x = 15;
            $y = 15;
            break;
        case '2':
            $x = $width1 - $new_width - 15;
            $y = 20;
            break;
        case '3':
            $x = 20;
            $y = $height1 - $new_height - 15;
            break;
        case '5':
            $x = ($width1 - $new_width) / 2;
            $y = ($height1 - $new_height) / 2;
            break;
        default:
            $x = $width1 - $new_width - 15;
            $y = $height1 - $new_height - 15;
            break;
    }

    // 创建透明画布,避免黑色
    if ($type1 == 1 || $type1 == 3) {
        $out = imagecreatetruecolor($width1, $height1);
        $color = imagecolorallocate($out, 255, 255, 255);
        imagefill($out, 0, 0, $color);
        imagecolortransparent($out, $color);
        imagecopy($out, $img1, 0, 0, 0, 0, $width1, $height1);
    } else {
        $out = $img1;
    }

    // 打上水印
    imagecopyresized($out, $img2, $x, $y - 10, 0, 0, $new_width, $new_height, $width2, $height2);
    check_dir(dirname($out_image), true); // 检查输出目录

    // 输出图片
    switch ($type1) {
        case 1:
            imagegif($out, $out_image, 90);
            break;
        case 2:
            imagejpeg($out, $out_image, 90);
            break;
        case 3:
            imagepng($out, $out_image, 90 / 10); // $quality参数取值范围0-99 在php 5.1.2之后变更为0-9
            break;
        default:
            imagejpeg($out, $out_image, 90);
    }
    imagedestroy($img1);
    imagedestroy($img2);
    return true;
}
// 获取删除按钮
function get_btn_del($idValue,$Model, $id = 'id', $btnName = '删除')
{
    $btn_html = "<a href='" . url("/".$Model."/del/$id/$idValue") . "' onclick='return confirm(\"您确定要删除么？\")' class='layui-btn layui-btn-xs layui-btn-danger' title='$btnName'>$btnName</a>";
    return $btn_html;
}
// 获取修改按钮
function get_btn_mod($idValue,$Model, $id = 'id', $btnName = '修改')
{
    $btn_html = "<a href='" . url("/".$Model."/mod/$id/$idValue")."'  class='layui-btn layui-btn-xs'>$btnName</a>";
    return $btn_html;
}
// 获取返回按钮
function get_btn_back($Model='',$btnName = '返 回')
{
    if (isset($_SERVER["HTTP_REFERER"])){

        $url = $_SERVER["HTTP_REFERER"];

    }else{
        $url = url($Model.'/index');
    }
    $btn_html = "<a href='" . $url . "' class='layui-btn layui-btn-primary'>$btnName</a>";
    return $btn_html;
}
// 获取按钮返回参数
function get_btn_qs()
{
    if (isset($_SERVER["QUERY_STRING"]) && ! ! $qs = $_SERVER["QUERY_STRING"]) {
        return "&backurl=" . base64_encode($_SERVER["QUERY_STRING"]);
    } else {
        return "?backurl=" . base64_encode($_SERVER["REQUEST_URI"]);
    }
}
// 获取字符串型自动编码
function get_auto_code($string, $start = '1')
{
    if (! $string)
        return $start;
    if (is_numeric($string)) { // 如果纯数字则直接加1
        return sprintf('%0' . strlen($string) . 's', $string + 1);
    } else { // 非纯数字则先分拆
        $reg = '/^([a-zA-Z-_]+)([0-9]+)$/';
        $str = preg_replace($reg, '$1', $string); // 字母部分
        $num = preg_replace($reg, '$2', $string); // 数字部分
        return $str . sprintf('%0' . (strlen($string) - strlen($str)) . 's', $num + 1);
    }
}
// 字符反转义html实体及斜杠，支持字符串、数组、对象
function decode_string($string)
{
    if (! $string)
        return $string;
    if (is_array($string)) { // 数组处理
        foreach ($string as $key => $value) {
            $string[$key] = decode_string($value);
        }
    } elseif (is_object($string)) { // 对象处理
        foreach ($string as $key => $value) {
            $string->$key = decode_string($value);
        }
    } else { // 字符串处理
        $string = stripcslashes($string);
        $string = htmlspecialchars_decode($string, ENT_QUOTES);
    }
    return $string;
}
// 检测指定的方法是否拥有权限
function check_level()
{
    $user_level = session('levels');
    if ($user_level==1) {
       return true;
   }
}
// 获取转义数据，支持字符串、数组、对象
function escape_string($string)
{
    if (! $string)
        return $string;
    if (is_array($string)) { // 数组处理
        foreach ($string as $key => $value) {
            $string[$key] = escape_string($value);
        }
    } elseif (is_object($string)) { // 对象处理
        foreach ($string as $key => $value) {
            $string->$key = escape_string($value);
        }
    } else { // 字符串处理
        $string = htmlspecialchars(trim($string), ENT_QUOTES, 'UTF-8');
        $string = addslashes($string);
    }
    return $string;
}
// 中英混合的字符串截取,以一个汉字为一个单位长度，英文为半个
function substr_both($string, $strat, $length)
{
    $s = 0; // 起始位置
    $i = 0; // 实际Byte计数
    $n = 0; // 字符串长度计数
    $str_length = strlen($string); // 字符串的字节长度
    while (($n < $length) and ($i < $str_length)) {
        $ascnum = Ord(substr($string, $i, 1)); // 得到字符串中第$i位字符的ascii码
        if ($ascnum >= 224) { // 根据UTF-8编码规范，将3个连续的字符计为单个字符
            $i += 3;
            $n ++;
        } elseif ($ascnum >= 192) { // 根据UTF-8编码规范，将2个连续的字符计为单个字符
            $i += 2;
            $n ++;
        } else {
            $i += 1;
            $n += 0.5;
        }
        if ($s == 0 && $strat > 0 && $n >= $strat) {
            $s = $i; // 记录起始位置
        }
    }
    if ($n < $strat) { // 起始位置大于字符串长度
        return;
    }
    return substr($string, $s, $i);
}

// 中英混合的字符串长度,以一个汉字为一个单位长度，英文为半个
function strlen_both($string)
{
    $i = 0; // 实际Byte计数
    $n = 0; // 字符串长度计数
    $str_length = strlen($string); // 字符串的字节长度
    while ($i < $str_length) {
        $ascnum = Ord(substr($string, $i, 1)); // 得到字符串中第$i位字符的ascii码
        if ($ascnum >= 224) { // 根据UTF-8编码规范，将3个连续的字符计为单个字符
            $i += 3;
            $n ++;
        } elseif ($ascnum >= 192) { // 根据UTF-8编码规范，将2个连续的字符计为单个字符
            $i += 2;
            $n ++;
        } else {
            $i += 1;
            $n += 0.5;
        }
    }
    return $n;
}
// 结果集中查找指定字段父节点是否存在
function result_value_search($needle, $result, $skey)
{
    foreach ($result as $key => $value) {
        if ($value->$skey == $needle) {
            return $key;
        }
    }
    return false;
}
// 获取字符串第N次出现位置
function get_strpos($string, $find, $n)
{
    $pos = strpos($string, $find);
    for ($i = 2; $i <= $n; $i ++) {
        $pos = strpos($string, $find, $pos + 1);
    }
    return $pos;
}

// 获取数据数组的映射数组
function get_mapping($array, $vValue, $vKey = null)
{
    if (!$array)
        return $array;
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            if ($vKey) {
                $result[$value[$vKey]] = $value[$vValue];
            } else {
                $result[] = $value[$vValue];
            }
        } elseif (is_object($value)) {
            if ($vKey) {
                $result[$value->$vKey] = $value->$vValue;
            } else {
                $result[] = $value->$vValue;
            }
        } else {
            return $array;
        }
    }
    return $result;
}
// 数组转换为带引号字符串
function implode_quot($glue, array $pieces, $diffnum = false)
{
    if (! $pieces)
        return "''";
    foreach ($pieces as $key => $value) {
        if ($diffnum && ! is_numeric($value)) {
            $value = "'$value'";
        } elseif (! $diffnum) {
            $value = "'$value'";
        }
        if (isset($string)) {
            $string .= $glue . $value;
        } else {
            $string = $value;
        }
    }
    return $string;
}
/**
 * 验证身份证合法性
 * @param  [type] $idcard [description]
 * @return [type]         [description]
 */
function checkIdCard($idcard){

    $City = array(11=>"北京",12=>"天津",13=>"河北",14=>"山西",15=>"内蒙古",21=>"辽宁",22=>"吉林",23=>"黑龙江",31=>"上海",32=>"江苏",33=>"浙江",34=>"安徽",35=>"福建",36=>"江西",37=>"山东",41=>"河南",42=>"湖北",43=>"湖南",44=>"广东",45=>"广西",46=>"海南",50=>"重庆",51=>"四川",52=>"贵州",53=>"云南",54=>"西藏",61=>"陕西",62=>"甘肃",63=>"青海",64=>"宁夏",65=>"新疆",71=>"台湾",81=>"香港",82=>"澳门",91=>"国外");
    $iSum = 0;
    $idCardLength = strlen($idcard);
    //长度验证
    if(!preg_match('/^\d{17}(\d|x)$/i',$idcard) and!preg_match('/^\d{15}$/i',$idcard))
    {
    	return false;
    }
    //地区验证
    if(!array_key_exists(intval(substr($idcard,0,2)),$City))
    {
    	return false;
    }
    // 15位身份证验证生日，转换为18位
    if ($idCardLength == 15)
    {
    	$sBirthday = '19'.substr($idcard,6,2).'-'.substr($idcard,8,2).'-'.substr($idcard,10,2);
    	$d = new DateTime($sBirthday);
    	$dd = $d->format('Y-m-d');
    	if($sBirthday != $dd)
    	{
    		return false;
    	}
    	$idcard = substr($idcard,0,6)."19".substr($idcard,6,9);//15to18
    	$Bit18 = getVerifyBit($idcard);//算出第18位校验码
    	$idcard = $idcard.$Bit18;
    }
    // 判断是否大于2078年，小于1900年
    $year = substr($idcard,6,4);
    if ($year<1900 || $year>2078 )
    {
    	return false;
    }

    //18位身份证处理
    $sBirthday = substr($idcard,6,4).'-'.substr($idcard,10,2).'-'.substr($idcard,12,2);
    $d = new DateTime($sBirthday);
    $dd = $d->format('Y-m-d');
    if($sBirthday != $dd)
    {
    	return false;
    }
    //身份证编码规范验证
    $idcard_base = substr($idcard,0,17);
    if(strtoupper(substr($idcard,17,1)) != getVerifyBit($idcard_base))
    {
    	return false;
    }
    return true;
}
//自定义调用子栏目
function navlist($scode,$limit=10){
	$ConModel = new ContentModel();
	if($scode > 0){
		$navlist=$ConModel->getSonScodes($scode,$limit);
	}else{
		$navlist=$ConModel->getSortList($scode,$limit);
	}

	return $navlist;
}
//自定义调用幻灯片 $gid, $num, $start = 1
function slides($gid, $num, $start = 1){
	$ConModel = new ContentModel();
	$slides=$ConModel->getSlides($gid, $num, $start);
	return $slides;
}
//自定义调用栏目内容不分页
//$scode(多个以逗号分割), $num, $order, $filter = array(), $tags = array(), $select = array(), $fuzzy = true, $start = 1
function contentlist($scode, $num, $order='id desc',$other='',$start = 1){
	$ConModel = new ContentModel();
	$list=$ConModel->getList($scode, $num,$order,$other, $start);
	return $list;
}
//调用栏目内容分页
//$scode(多个以逗号分割), $num, $order, $filter = array(), $tags = array(), $select = array(), $fuzzy = true, $start = 1
function lists($scode, $num, $order='id desc',$other='',$run1=0,$run2=0,$run3=0) {
	$ConModel = new ContentModel();
	$list=$ConModel->getLists($scode, $num,$order,$other,$run1,$run2,$run3);
	return $list;
}

//指定内容调用
function content($id){
	$ConModel = new ContentModel();
	$content=$ConModel->getContent($id);
	return $content;
} 

//单页指定内容调用
function About($scode){
	$ConModel = new ContentModel();
	$content=$ConModel->getAbout($scode);
	return $content;
} 


//获取顶级栏目名称
function getTopScode($scode){
	$ConModel = new ContentModel();
	$sort=$ConModel->getSortTopScode($scode);
	$topname=$ConModel->getSortName($sort);
	return $topname;
}
//获取顶级栏目ID
function getTopcode($scode){
	$ConModel = new ContentModel();
	$sort=$ConModel->getSortTopScode($scode);
	return $sort;
}
//获取顶级栏目详情
function getTopCodeInfo($scode,$filed){
	$ConModel = new ContentModel();
	$sort=$ConModel->getSortTopScode($scode);
	$sortinfo=$ConModel->getTSortinfo($sort);
	return $sortinfo[$filed];
}
//获取当前栏目详情
function getScodeInfo($scode,$filed){
	$ConModel = new ContentModel();
	$sortinfo=$ConModel->getSortinfo($scode);
	return $sortinfo[$filed];
}
//当前位置设置
function getCurrent($scode){
	$ConModel = new ContentModel();
	$data=$ConModel->getPosition($scode);
		$out_html = '<a href="' . url('/').'">首 页</a> >';
		foreach ($data as $key => $value) {
			if ($value['outlink']) {
				$out_html .=' <a href="' . $value['outlink'] . '">' . $value['name'] . '</a>   > ';
			} else {
				if($value['type']!=1){
					$out_html .= ' <a href="'.url($value['urlname'].'list',['tid'=>$value['scode']]).'">'. $value['name'] . '</a>  > ';
				}else{
					$out_html .=' <a href="'.url($value['urlname'],['tid'=>$value['scode']]).'">'. $value['name'] . '</a>  > ';
				}
			}
		}
	return $out_html;
}

//自定义调用友情链接 $gid, $num, $start = 1
function links($gid, $num, $start = 1){
	$ConModel = new ContentModel();
	$links=$ConModel->getLinks($gid, $num, $start);
	return $links;
}
//返回关联文章标题
function getcontentfield($id,$filed){
	$ConModel = new ContentModel();
	$result=$ConModel->getcontentfield($id,$filed);
	return $result;
}
//返回关联文章标题
function getcontentExfield($id,$filed){
	$ConModel = new ContentModel();
	$result=$ConModel->getContentExt($id,$filed);
	return $result;
}
function getwholelist($TypeID,$mcode,$scode=''){
	$ConModel = new ContentModel();
	$result=$ConModel->GetWholeType($TypeID,$mcode,$scode);
	return $result;
} 

//返回whole分类字段
function get_whole_field($id,$filed='TypeName'){
	$ConModel = new ContentModel();
	$result=$ConModel->getWholeField($id,$filed);
	return $result;
}